<template>
    <layout>
        <div class="lock">
            <div class="main-img">
                <img :src="unlock" />
            </div>
            <p class="welcome">您好<span class="user">{{ userInfo.id }}</span>,您已登录{{ loginTime }}</p>
            <div class="buttons">
                <el-button size="large" type="primary" @click="openMain">
                    <div class="img-button"><img :src="tick" alt=""><span>进入EAP</span></div>
                </el-button>
                <el-button size="large" @click="logout">
                    <div class="img-button"><img :src="power" alt=""><span>注销EAP</span></div>
                </el-button>
            </div>
            <!-- {{ userInfo.id }}
            <button @click="openMain">打开主页</button>
            <button @click="openMain1">打开主页1</button>
            <button @click="logout">注销</button> -->
        </div>
    </layout>

</template>
<script setup>
import { useUserStore } from "@/store/userStore";
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRouter } from 'vue-router'
import { ipcApiRoute } from "@/api";
import { ipc, isEE } from "@/utils/ipcRenderer";
import { ElMessage } from 'element-plus'
import unlock from '@/assets/images/unlock.png'
import tick from '@/assets/images/tick.png'
import power from '@/assets/images/power.png'
import layout from "./layout.vue";
const loginTime = ref("");
const userStore = useUserStore()
let userInfo = reactive({})
const requesting = ref(false);
const router = useRouter()
userStore.getUserInfo().then(user => {
    Object.assign(userInfo, user);
})

//进入主页面
function openMain() {
    ipc.invoke(ipcApiRoute.openMain, {}).then(result => {
        if (!result.success) {
            ElMessage.error("进入EAP失败,登录超时,请重新登录");
            router.push({ path: "/login" })
        }
    });
}

//退出
function logout() {
    requesting.value = true;
    userStore.logout().then(res => {

        router.push({ path: "/login" })

    })
}
function calculateLoginTime() {

    // 将输入转换为 Date 对象
    let start = new Date();
    const end = new Date();
    if (userInfo && userInfo.loginTime)
        start = userInfo.loginTime;
    // 计算时间差（毫秒）
    const differenceMs = end - start;

    // 处理时间差为负的情况
    if (differenceMs < 0) {
        throw new Error('结束时间不能早于开始时间');
    }

    // 计算小时、分钟和秒
    const totalSeconds = Math.floor(differenceMs / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;

    // 格式化为 00小时00分00秒 的形式
    loginTime.value = `${padZero(hours)}小时${padZero(minutes)}分${padZero(seconds)}秒`;
    function padZero(num) {
        return num < 10 ? `0${num}` : num.toString();
    }
}


const handleProtocolCall = () => {
    if (!isEE) {
        return;
    }
    ipc.on('protocol-call', (event, data) => {
        if (data.protocol == "logout") {
            logout()
        }
    });
};

const logoutSuccess = () => {
    if (!isEE) {
        return;
    }
    ipc.on('web-logout-success', (event, data) => {
        console.log('退出成功:', data);
        router.push({ path: "/login" })
    });
};



onMounted(() => {
    //loginTime.value = "00小时00分00秒";
    calculateLoginTime();
    setInterval(() => {
        calculateLoginTime();
    }, 1000)

    handleProtocolCall()
    logoutSuccess();
})

onUnmounted(() => {
    ipc.removeAllListeners('protocol-call');
    ipc.removeAllListeners('web-login-success');
});

</script>
<style scoped lang="less">
.lock {
    padding: 0 10px;
    flex: 1;

    .main-img {
        margin: 0 auto;
        margin-top: 15px;
    }

    .welcome {
        font-size: 18px;

        .user {
            color: #FFA67F;
        }
    }

    .buttons {
        margin-top: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 20px;
    }

    .img-button {

        display: flex;
        align-items: center;
        justify-content: center;
        gap: 10px;

        span {
            font-size: 18px;
        }
    }
}
</style>